using Godot;
using System;
using CurrentGame.Utils.Interpolation;


public partial class LightActionHint : Sprite2D
{
	[Signal]
	public delegate void ActionFinishedEventHandler();

	[Export]
	public float InterpolationWeight
	{
		get => _interpolation.Weight;
		set => _interpolation.Weight = value;
	}
	[Export]
	public float ScaleOffset { get; set; } = 0.2f;
	[Export]
	public float ScaleFactor { get; set; } = 6.0f;

	[Export]
	public Player MainPlayer { get; set; }
	[Export]
	public CinematicCamera Camera { get; set; }


	private bool _animating = false;
	private LerpInterpolation _interpolation;
	private Vector2 _center;


	public LightActionHint()
	{
		_interpolation = new LerpInterpolation(0.01f, new Vector3(-1f, 0.000001f, -1f))
		{
			Vector2Value = new Vector2(1.0f, 0.0f)	// alpha, scale
		};
		_interpolation.Teleport();
		_interpolation.ReachStableValue += Signal_InterpolationStable;
	}

    public override void _Ready()
    {
		_center = (Vector2)Camera.CameraRawSize / 2.0f;
    }

    public override void _PhysicsProcess(double delta)
    {
		var position = MainPlayer.GlobalPosition - Camera.GlobalPosition;
		position *= Camera.Zoom;
		GlobalPosition = _center + position;
    }

	public override void _Process(double delta)
	{
		if (_interpolation.Process(delta))
		{
			var current = _interpolation.Vector2Value;
			Modulate = new Color(1.0f, 1.0f, 1.0f, current.X);
			Scale = new Vector2(current.Y, current.Y);
		}
	}

	public void StartAnimation(int level)
	{
		_animating = true;
		float scale = (float)level / ScaleFactor + ScaleOffset;
		_interpolation.Vector2Value = new Vector2(0.0f, scale * Camera.Zoom);
	}

	// Signals
	private void Signal_InterpolationStable(float v, Vector2 v2, Vector3 v3)
	{
		// Action is performing
		if (_animating)
		{
			EmitSignal(SignalName.ActionFinished);
			_interpolation.Vector2Value = new Vector2(1.0f, 0.0f);
			_interpolation.Teleport();

			Scale = new Vector2(0.0f, 0.0f);
			ResetPhysicsInterpolation();

			_animating = false;
		}
	}
}
